/**
 * @Description : 文件管理模块
 **/
const userModel = require("../model/userModel");
const userFileModel = require("../model/userFileModel");
const { output } = require("../common/index");
const qs = require("qs");
const fs = require("fs");

const file = async (req, res) => {
    try {
        var tmpRequest = req.body ? qs.parse(req.body) : {}; //获取表单或参数内容
        console.log("file tmpRequest", tmpRequest);
        var code = 1;
        var msg = "成功";

        if (tmpRequest.type == "1") {
            if (tmpRequest.op == "1") {
                var count = 0;
                var list = {};
                await userModel
                    .aggregate([
                        {
                            $unwind: "$folder_list"
                        },
                        {
                            $match: {
                                "folder_list.folder_status": 1,
                                status: 1,
                                account: tmpRequest.account
                            }
                        },
                        { $count: "count" }
                    ])
                    .then((result) => {
                        if (result && result[0] && result[0].count) {
                            count = result[0].count;
                        }
                    })
                    .catch((err) => {
                        output(res, { code: 2, msg: "查询数据数量操作错误" + JSON.stringify(err) });
                    });
                if (count > 0) {
                    await userModel
                        .aggregate([
                            {
                                $unwind: "$folder_list"
                            },
                            {
                                $match: {
                                    "folder_list.folder_status": 1,
                                    status: 1,
                                    account: tmpRequest.account
                                }
                            },
                            {
                                $project: {
                                    _id: 0,
                                    value: "$folder_list.id",
                                    label: "$folder_list.folder_name",
                                    parent_id: "$folder_list.parent_id",
                                    memo: "$folder_list.folder_memo"
                                }
                            }
                        ])
                        .then((result) => {
                            list = func_recursData(result, "");
                        })
                        .catch((err) => {
                            output(res, { code: 2, msg: "查询数据数量操作错误" + JSON.stringify(err) });
                        });
                }
                output(res, { code: code, msg: msg, data: { count: count, list: list } });
            } else if (tmpRequest.op == "2") {
                let formData = tmpRequest.formData ? JSON.parse(tmpRequest.formData) : "";
                let folder_list = {};
                folder_list.id = Date.now();
                folder_list.parent_id = formData.parent_id ?? "";
                folder_list.folder_name = formData.folder_name;
                folder_list.folder_status = 1;
                folder_list.folder_update_time = new Date().toLocaleString();

                await userModel
                    .updateOne(
                        {
                            status: 1,
                            account: tmpRequest.account
                        },
                        {
                            $push: {
                                folder_list: folder_list
                            }
                        }
                    )
                    .then((result) => {
                        if (result.acknowledged && result.modifiedCount > 0) {
                            code = 1;
                            msg = "新增数据成功";
                        } else {
                            code = 2;
                            msg = "新增数据失败";
                        }
                        output(res, { code: code, msg: msg, data: {} });
                    })
                    .catch((err) => {
                        output(res, { code: 2, msg: "新增数据操作错误" + JSON.stringify(err) });
                    });
            } else if (tmpRequest.op == "3") {
                let updateCount = 0;
                let formData = tmpRequest.formData ? JSON.parse(tmpRequest.formData) : "";
                await userModel
                    .aggregate([
                        {
                            $unwind: "$folder_list"
                        },
                        {
                            $match: {
                                "folder_list.folder_status": 1,
                                "folder_list.id": formData.id,
                                status: 1,
                                account: tmpRequest.account
                            }
                        },
                        { $count: "count" }
                    ])
                    .then((result) => {
                        if (result && result[0] && result[0].count) {
                            updateCount = result[0].count;
                        } else {
                            output(res, { code: 2, msg: "修改的数据不存在" });
                        }
                    })
                    .catch((err) => {
                        output(res, { code: 2, msg: "查询数据数量操作错误" + JSON.stringify(err) });
                    });

                if (updateCount > 0) {
                    await userModel
                        .updateOne(
                            {
                                status: 1,
                                account: tmpRequest.account
                            },
                            {
                                $set: {
                                    "folder_list.$[tx].folder_name": formData.folder_name,
                                    "folder_list.$[tx].folder_update_time": new Date().toLocaleString()
                                }
                            },
                            {
                                arrayFilters: [
                                    {
                                        "tx.id": formData.id,
                                        "tx.folder_status": 1
                                    }
                                ]
                            }
                        )
                        .then((result) => {
                            if (result.acknowledged && result.modifiedCount > 0) {
                                code = 1;
                                msg = "修改数据成功";
                            } else {
                                code = 2;
                                msg = "修改数据失败";
                            }
                            output(res, { code: code, msg: msg, data: {} });
                        })
                        .catch((err) => {
                            output(res, { code: 2, msg: "新增数据操作错误" + JSON.stringify(err) });
                        });
                }
            } else if (tmpRequest.op == "4") {
                let deleteCount = 0;
                let formData = tmpRequest.formData ? JSON.parse(tmpRequest.formData) : "";
                await userModel
                    .aggregate([
                        {
                            $match: {
                                "folder_list.folder_status": 1,
                                "folder_list.id": formData,
                                status: 1,
                                account: tmpRequest.account
                            }
                        },
                        {
                            $unwind: "$folder_list"
                        },
                        { $count: "count" }
                    ])
                    .then((result) => {
                        if (result && result[0] && result[0].count) {
                            deleteCount = result[0].count;
                        } else {
                            output(res, { code: 2, msg: "删除的数据不存在" });
                        }
                    })
                    .catch((err) => {
                        output(res, { code: 2, msg: "查询数据数量操作错误" + JSON.stringify(err) });
                    });

                if (deleteCount > 0) {
                    await userModel
                        .updateOne(
                            {
                                status: 1,
                                account: tmpRequest.account
                            },
                            {
                                $set: {
                                    "folder_list.$[tx].folder_status": 0,
                                    "folder_list.$[tx].folder_update_time": new Date().toLocaleString()
                                }
                            },
                            {
                                arrayFilters: [
                                    {
                                        "tx.id": formData,
                                        "tx.folder_status": 1
                                    }
                                ]
                            }
                        )
                        .then((result) => {
                            if (result.acknowledged && result.modifiedCount > 0) {
                                code = 1;
                                msg = "删除数据成功";
                            } else {
                                code = 2;
                                msg = "删除数据失败";
                            }
                            output(res, { code: code, msg: msg, data: {} });
                        })
                        .catch((err) => {
                            output(res, { code: 2, msg: "新增数据操作错误" + JSON.stringify(err) });
                        });
                }
            }
        } else if (tmpRequest.type == "2") {
            if (tmpRequest.op == "1") {
                var count = 0;
                var list = {};
                var tmpMatch = {
                    status: 1,
                    account: tmpRequest.account
                };
                if (tmpRequest.type_id) {
                    tmpMatch.folder_id = { $in: tmpRequest.type_id };
                }

                await userFileModel
                    .aggregate([{ $match: tmpMatch }, { $count: "count" }])
                    .then((result) => {
                        if (result && result[0] && result[0].count > 0) {
                            count = result[0].count;
                        }
                    })
                    .catch((err) => {
                        output(res, { code: 2, msg: "查询数据数量操作错误" + JSON.stringify(err) });
                    });
                if (count > 0) {
                    await userFileModel
                        .aggregate([
                            {
                                $match: tmpMatch
                            },
                            {
                                $project: {
                                    _id: 0,
                                    id: 1,
                                    folder_id: 1,
                                    folder_name: 1,
                                    file_name: 1,
                                    file_old_name: 1,
                                    file_type: 1,
                                    file_suffix: 1,
                                    file_url: 1
                                }
                            },
                            { $skip: (parseInt(tmpRequest.page ?? 1) - 1) * parseInt(tmpRequest.pageNum ?? 30) },
                            { $limit: parseInt(tmpRequest.pageNum ?? 30) }
                        ])
                        .then((result) => {
                            list = result;
                            list.forEach((item, index) => {
                                if (item.file_url) {
                                    list[index].file_path =
                                        process.env.API_DOMAIN_URL + "user/file/view?filename=" + item.id;
                                    delete list[index].file_url;
                                }
                            });
                        })
                        .catch((err) => {
                            output(res, { code: 2, msg: "查询数据数量操作错误" + JSON.stringify(err) });
                        });
                }
                output(res, { code: code, msg: msg, data: { count: count, list: list } });
            } else if (tmpRequest.op == "2") {
            } else if (tmpRequest.op == "3") {
                let updateCount = 0;
                let formData = tmpRequest.formData ? JSON.parse(tmpRequest.formData) : "";
                await userFileModel
                    .aggregate([
                        {
                            $match: {
                                id: formData.value,
                                folder_id: formData.editTypeId,
                                status: 1,
                                account: tmpRequest.account
                            }
                        },
                        { $count: "count" }
                    ])
                    .then((result) => {
                        if (result && result[0] && result[0].count) {
                            updateCount = result[0].count;
                        } else {
                            output(res, { code: 2, msg: "修改的数据不存在" });
                        }
                    })
                    .catch((err) => {
                        output(res, { code: 2, msg: "查询数据数量操作错误" + JSON.stringify(err) });
                    });

                if (updateCount > 0) {
                    await userFileModel
                        .updateOne(
                            {
                                id: formData.value,
                                folder_id: formData.editTypeId,
                                status: 1,
                                account: tmpRequest.account
                            },
                            {
                                $set: {
                                    folder_id: formData.new_type_id,
                                    update_user: tmpRequest.account,
                                    update_time: new Date().toLocaleString()
                                }
                            }
                        )
                        .then((result) => {
                            if (result.acknowledged && result.modifiedCount > 0) {
                                code = 1;
                                msg = "修改数据成功";
                            } else {
                                code = 2;
                                msg = "修改数据失败";
                            }
                            output(res, { code: code, msg: msg, data: {} });
                        })
                        .catch((err) => {
                            output(res, { code: 2, msg: "修改数据操作错误" + JSON.stringify(err) });
                        });
                }
            } else if (tmpRequest.op == "4") {
                let deleteCount = 0;
                let formData = tmpRequest.formData ? JSON.parse(tmpRequest.formData) : "";

                await userFileModel
                    .aggregate([
                        {
                            $match: {
                                id: { $in: formData },
                                status: 1,
                                account: tmpRequest.account
                            }
                        },
                        { $count: "count" }
                    ])
                    .then((result) => {
                        console.log("del count", result);
                        if (result && result[0] && result[0].count) {
                            deleteCount = result[0].count;
                        } else {
                            output(res, { code: 2, msg: "删除的数据不存在" });
                        }
                    })
                    .catch((err) => {
                        output(res, { code: 2, msg: "查询数据数量操作错误" + JSON.stringify(err) });
                    });

                if (deleteCount > 0) {
                    await userFileModel
                        .updateMany(
                            {
                                id: { $in: formData },
                                status: 1,
                                account: tmpRequest.account
                            },
                            {
                                $set: {
                                    status: 0,
                                    delete_user: tmpRequest.account,
                                    delete_time: new Date().toLocaleString()
                                }
                            }
                        )
                        .then((result) => {
                            console.log("del result", result);

                            if (result.acknowledged && result.modifiedCount > 0) {
                                code = 1;
                                msg = "删除数据成功";
                            } else {
                                code = 2;
                                msg = "删除数据失败";
                            }
                            output(res, { code: code, msg: msg, data: {} });
                        })
                        .catch((err) => {
                            output(res, { code: 2, msg: "删除数据操作错误" + JSON.stringify(err) });
                        });
                }
            }
        }
    } catch (error) {
        output(res, { code: 2, msg: "操作错误" + JSON.stringify(error) });
    }
};

//查看文件
const view = async function (req, res) {
    try {
        if (req.query.filepath) {
            let file = process.env.UPLOAD_DIR + req.query.filepath;
            if (!fs.existsSync(file)) {
                output(res, { code: 2, msg: "文件不存在" });
            } else {
                // let mimetype;
                // if (mime.lookup) {
                //     mimetype = mime.lookup(file);
                // } else mimetype = mime.getType(file);
                // res.setHeader("Content-type", mimetype + "; charset=utf-8");
                res.sendfile(file);
            }
        } else if (req.query.filename) {
            //通过id查询文件是否存在
            var count = 0;
            var list = {};
            await userFileModel
                .aggregate([{ $match: { status: 1, id: req.query.filename } }, { $count: "count" }])
                .then((result) => {
                    if (result && result[0] && result[0].count > 0) {
                        count = result[0].count;
                    }
                })
                .catch((err) => {
                    output(res, { code: 2, msg: "查询数据数量操作错误" + JSON.stringify(err) });
                });

            if (count) {
                await userFileModel
                    .aggregate([{ $match: { status: 1, id: req.query.filename } }])
                    .then((result) => {
                        //查询集合数据集
                        list = result;
                    })
                    .catch((err) => {
                        output(res, { code: 2, msg: "查询数据操作错误" + JSON.stringify(err) });
                    });

                if (list[0].file_name && list[0].file_url) {
                    let file = process.env.UPLOAD_DIR + list[0].file_url;
                    if (!fs.existsSync(file)) {
                        output(res, { code: 2, msg: "文件不存在" });
                    } else {
                        res.sendfile(file);
                    }
                } else {
                    output(res, { code: 2, msg: "无此文件" });
                }
            } else {
                output(res, { code: 2, msg: "文件记录不存在" });
            }
        } else {
            output(res, { code: 2, msg: "非法文件访问" });
        }
    } catch (error) {
        output(res, { code: 2, msg: "操作错误" + JSON.stringify(error) });
    }
};

/**
 * 递归数据内容
 */
const func_recursData = (data, pid, field = "parent_id") => {
    var outArr = [];
    if (data.length > 0) {
        for (var i in data) {
            if (data[i][field] == pid) {
                var children = func_recursData(data, data[i].value, field);
                data[i].children = children.length ? children : [];
                outArr.push(data[i]);
            }
        }
    }
    return outArr;
};

module.exports = { file, view };
